package thread.juc.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;

/**
 * 闭锁：在完成某些运算时，只有其他（线程）运算全部完成，当前运算才会继续执行
 * 计算多线程同时执行的时间
 */
public class TestCountdownlatch {
    public static void main(String[] args) {
        final CountDownLatch countDownLatch = new CountDownLatch(5);//线程操作递减1 为0 任务完成
        LatchDemo latchDemo = new LatchDemo(countDownLatch);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5; i++) {
            new Thread(latchDemo).start();
        }
        try {
            countDownLatch.await();//注掉看效果
            long stop = System.currentTimeMillis();
            System.out.println("耗费时间为：" + (stop - start) + "/ms\r");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class LatchDemo implements Runnable {

    private CountDownLatch latch;

    public LatchDemo() {
    }

    public LatchDemo(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            for (int i = 0; i < 5000; i++) {
                if (i % 2 == 0) {
                    System.out.println(i);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            latch.countDown();//闭锁减1
        }
    }
}
